import request from './index'

export interface JudgeRequest {
  problem_id: number
  language: string
  code: string
}

export interface JudgeResult {
  status: string
  score: number
  max_score: number
  test_cases: any[]
  execution_time?: number
  memory_usage?: number
  error_message?: string
}

export interface AsyncJudgeResponse {
  task_id: string
  status: string
}

export interface JudgeStatusResponse {
  task_id: string
  status: string
  result?: JudgeResult
  error_message?: string
  created_at: number
  started_at?: number
  completed_at?: number
}

export interface QueueStatusResponse {
  queue_size: number
  max_queue_size: number
  active_workers: number
  max_workers: number
  pending_tasks: number
  running_tasks: number
  completed_tasks: number
}

// 兼容旧的API调用方式
export const judgeApi = {
  // 运行代码（不保存提交记录）
  runCode(data: JudgeRequest): Promise<JudgeResult> {
    return request({
      url: '/judge/run',
      method: 'post',
      data
    })
  },

  // 提交代码（保存提交记录）
  submitCode(data: JudgeRequest): Promise<JudgeResult> {
    return request({
      url: '/judge/submit',
      method: 'post',
      data
    })
  },

  // 获取提交历史
  getSubmissions(problemId?: number): Promise<any> {
    const params = problemId ? { problem_id: problemId } : {}
    return request({
      url: '/submissions',
      method: 'get',
      params
    })
  },

  // 获取提交详情
  getSubmission(submissionId: number): Promise<any> {
    return request({
      url: `/submissions/${submissionId}`,
      method: 'get'
    })
  }
}

// 新的异步判题API
// 同步运行代码（不保存提交记录）
export function runCode(data: JudgeRequest) {
  return request({
    url: '/judge/run',
    method: 'post',
    data
  })
}

// 同步提交代码（保存提交记录）
export function submitCode(data: JudgeRequest) {
  return request({
    url: '/judge/submit',
    method: 'post',
    data
  })
}

// 异步提交代码
export function submitCodeAsync(data: JudgeRequest): Promise<AsyncJudgeResponse> {
  return request({
    url: '/judge/submit-async',
    method: 'post',
    data
  })
}

// 获取判题状态
export function getJudgeStatus(taskId: string): Promise<JudgeStatusResponse> {
  return request({
    url: `/judge/status/${taskId}`,
    method: 'get'
  })
}

// 获取队列状态
export function getQueueStatus(): Promise<QueueStatusResponse> {
  return request({
    url: '/judge/queue-status',
    method: 'get'
  })
}
